/**
 * projectName:
 * fileName:
 * packageName:
 * date:
 * copyright(c) 2017-2020 xxx公司
 */
package cn.horesman.service.impl;

import cn.horesman.service.HoresmanService;
import cn.itcast.mapper.*;
import cn.itcast.pojo.*;
import cn.itcast.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import java.util.Date;

import static cn.itcast.util.Date.getTimesevening;
import static cn.itcast.util.Date.getTimesmorning;



/**
 * @title: userServiceImpl.java
 * @package com.job.service.lmpl
 * @description: TODO
 * @author: 欧阳辉
 * @date: 2019年1月25日 下午3:21:04 
 * @version: V1.0
 */
@Slf4j
@Service
public class HoresmanServiceImpl implements HoresmanService {

    @Resource
    private  baidudituController baidudituController;

    /*@Resource
    private RedisTemplate template;*/
    @Resource
    cn.itcast.mapper.orderMapper orderMapper;
    @Resource
    cn.itcast.mapper.orderItemMapper orderItemMapper;
    @Resource
    horsemanMapper horsemanMapper;
    @Resource
    userMapper userMapper;

    @Resource
    classsifyMapper classsifyMapper;

    @Resource
    accountMapper accountMapper;

    @Resource
    earningsMapper earningsMapper;

    @Resource
    gzhMapper gzhMapper;

    @Resource
    merchantMapper merchantMapper;

    @Resource
    packageOrderMapper packageOrderMapper;

    @Resource
    packageOrderItemMapper packageOrderItemMapper;

    @Resource
    infoMapper infoMapper;

    @Resource
    CookieUtil cookieUtil;

    @Resource
    private Distance distance;

    @Autowired
    RedisUtil redisTemplate;

    @Resource
    packageClassifyMapper packageClassifyMapper;

    @Resource
    private user_addressMapper addressMapper;


    @Override
    public Map<String, Object> login(String username, String password) {
        //返回Map
        Map<String, Object> map = new HashMap<String, Object>();
        boolean islogin = true;
        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andHorsemanNumberEqualTo(username);
        List<horseman> horsemens = horsemanMapper.selectByExample(hEx);
        if (!horsemens.isEmpty()) {
            if (horsemens.get(0).getHorsemanIsopen().equals("0")) {
                //如果账号审核未通过或者已关闭，返回no
                map.put("horsemen", "no");
                map.put("islogin", true);
                return map;
            }
            String pwd = horsemens.get(0).getHorsemanPassword();
            if (password.equals(pwd)) {
                //管理员数据返回前台
                map.put("horsemen", horsemens.get(0));
                map.put("islogin", islogin);
                //System.out.println(template.opsForValue().get(token));
                log.debug(horsemens.get(0).getHorsemanNumber());
            } else {
                islogin = false;
                map.put("horsemen", "");
                map.put("islogin", islogin);
                log.debug("密码错误");
            }
        } else {
            islogin = false;
            map.put("horsemen", "");
            map.put("islogin", islogin);
            log.debug("用户不存在");
        }
        return map;
    }

    /**
     *
     * @Description:
     * 获取用户各状态订单
     * @auther: 欧阳辉
     * @date: 11:36 2020/3/17
     * @param: [orderStatus, openId]
     * @return: java.util.List<cn.itcast.pojo.order>
     *
     */
//    @Override
//    public PageInfo findHoresmanOrder(String orderStatus, String openId,Integer page) {
//        log.debug(orderStatus + "openId" + openId);
//        orderExample oEx = new orderExample();
//        oEx.setOrderByClause("order_time DESC");
//        orderExample.Criteria criteria = oEx.createCriteria();
//        criteria.andHorsemanAccountEqualTo(openId);
//        criteria.andOrderStateEqualTo(orderStatus);
//        PageHelper.startPage(page,5);
//        List<order> orders = orderMapper.selectByExample(oEx);
//        PageInfo pageinfo = new PageInfo(orders);
//        List<order> pageinfoOrders = pageinfo.getList();
//
//        for (int i = 0; i < pageinfoOrders.size(); i++) {
//            orderItemExample oIEx = new orderItemExample();
//            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
//            criteria1.andOrderIdEqualTo(pageinfoOrders.get(i).getId());
//            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
//            pageinfoOrders.get(i).setOrderItems(orderItems);
//
//            if(orderStatus.equals("进行中")){
//                //用户信息
//                HashMap<String,String> userInfo = new HashMap<>();
//
//                userExample userExample = new userExample();
//                cn.itcast.pojo.userExample.Criteria criteria2 = userExample.createCriteria();
//                criteria2.andOpenIdEqualTo(pageinfoOrders.get(i).getOpenId());
//                List<user> userList = userMapper.selectByExample(userExample);
//
//                userInfo.put("orderId",String.valueOf(pageinfoOrders.get(i).getId())); //电话
//                userInfo.put("userName",userList.get(0).getUserName()); //用户名
//                userInfo.put("avatarUrl",userList.get(0).getAvatarUrl());//用户头像
//                userInfo.put("userPhone",userList.get(0).getUserPhone()); //电话
////                String substring1 = null;
////
////                String address = orders.get(i).getUserArea();
////                String addressOne = orders.get(i).getCounty();	//从这个切
////                String substring = addressOne.substring(addressOne.length() - 1, addressOne.length());
////                int i1 = address.indexOf(substring);
////                substring1 = address.substring(i1 + 1, address.length());
//
//
////                int flag = substring1.indexOf("东莞市");
////
////                if(flag == 0){
////                    String ok = substring1.replaceAll("^(东莞市)", "");
////                    substring1 = ok;
////                }
////
////                log.info("substring1地址这里：{}",substring1);
//
//                //获取订单用户的openId 通过用户openId获取用户收货地址
////                user_addressExample user_addressExample = new user_addressExample();
////                cn.itcast.pojo.user_addressExample.Criteria criteria3 = user_addressExample.createCriteria();
////                criteria3.andOpenIdEqualTo(orders.get(i).getOpenId());
////                criteria3.andDetailAddressEqualTo(substring1);
////                List<user_address> addresses = addressMapper.selectByExample(user_addressExample);
////
////
////
////                //用户地址
////                String userAddress = addresses.get(0).getProvince()
////                        +addresses.get(0).getCity()
////                        +addresses.get(0).getCounty()
////                        +addresses.get(0).getDetailAddress();
////                //获取用户地址经纬度
////
////                Map<String,Double> mapAddress =baidudituController.getCoordinate(userAddress);
//
//                //经纬度
//                userInfo.put("lng",pageinfoOrders.get(i).getLon());
//                userInfo.put("lat",pageinfoOrders.get(i).getLat());
//                pageinfoOrders.get(i).setUserInfo(userInfo);
//            }
//        }
//        return pageinfo;
//
//    }


    @Override
    public List<order> findHoresmanOrder(String orderStatus, String openId) {
        log.debug(orderStatus + "openId" + openId);
        orderExample oEx = new orderExample();
        if(orderStatus.equals("待接单") || orderStatus.equals("异常订单")){
            //下单时间
            oEx.setOrderByClause("order_time DESC");
        }
        if (orderStatus.equals("进行中")){
            //接单时间
            oEx.setOrderByClause("horseman_reception_time DESC");
        }
        if (orderStatus.equals("待支付")){
            //计量时间
            oEx.setOrderByClause("horseman_measure_time DESC");
        }
        if (orderStatus.equals("已完成")){
            //支付时间
            oEx.setOrderByClause("pay_time DESC");
        }
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andHorsemanAccountEqualTo(openId);
        criteria.andOrderStateEqualTo(orderStatus);
        PageHelper.startPage(1,50);
        List<order> orders = orderMapper.selectByExample(oEx);
        PageInfo pageinfo = new PageInfo(orders);

        for (int i = 0; i < orders.size(); i++) {
            orderItemExample oIEx = new orderItemExample();
            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(orders.get(i).getId());
            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
            orders.get(i).setOrderItems(orderItems);

            if(orderStatus.equals("进行中")){
                //用户信息
                HashMap<String,String> userInfo = new HashMap<>();

                userExample userExample = new userExample();
                cn.itcast.pojo.userExample.Criteria criteria2 = userExample.createCriteria();
                criteria2.andOpenIdEqualTo(orders.get(i).getOpenId());
                List<user> userList = userMapper.selectByExample(userExample);

                userInfo.put("orderId",String.valueOf(orders.get(i).getId())); //电话
                userInfo.put("userName",userList.get(0).getUserName()); //用户名
                userInfo.put("avatarUrl",userList.get(0).getAvatarUrl());//用户头像
                userInfo.put("userPhone",userList.get(0).getUserPhone()); //电话

                //经纬度
                userInfo.put("lng",orders.get(i).getLon());
                userInfo.put("lat",orders.get(i).getLat());
                orders.get(i).setUserInfo(userInfo);
            }
        }
        return orders;
    }

    @Override
    public List<order> findmerchantOrder(String orderStatus ,String merchantopenid) {
        orderExample oEx = new orderExample();
        if(orderStatus.equals("待接单") || orderStatus.equals("异常订单")){
            //下单时间
            oEx.setOrderByClause("order_time DESC");
        }
        if (orderStatus.equals("进行中")){
            //接单时间
            oEx.setOrderByClause("horseman_reception_time DESC");
        }
        if (orderStatus.equals("待支付")){
            //计量时间
            oEx.setOrderByClause("horseman_measure_time DESC");
        }
        if (orderStatus.equals("已完成")){
            //支付时间
            oEx.setOrderByClause("pay_time DESC");
        }
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andmerchant_openid(merchantopenid);
        criteria.andOrderStateEqualTo(orderStatus);
        PageHelper.startPage(1,50);
        List<order> orders = orderMapper.selectByExample(oEx);
        PageInfo pageinfo = new PageInfo(orders);

        for (int i = 0; i < orders.size(); i++) {
            orderItemExample oIEx = new orderItemExample();
            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(orders.get(i).getId());
            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
            orders.get(i).setOrderItems(orderItems);

            if(orderStatus.equals("进行中")){
                //用户信息
                HashMap<String,String> userInfo = new HashMap<>();

                userExample userExample = new userExample();
                cn.itcast.pojo.userExample.Criteria criteria2 = userExample.createCriteria();
                criteria2.andOpenIdEqualTo(orders.get(i).getOpenId());
                List<user> userList = userMapper.selectByExample(userExample);

                userInfo.put("orderId",String.valueOf(orders.get(i).getId())); //电话
                userInfo.put("userName",userList.get(0).getUserName()); //用户名
                userInfo.put("avatarUrl",userList.get(0).getAvatarUrl());//用户头像
                userInfo.put("userPhone",userList.get(0).getUserPhone()); //电话

                //经纬度
                userInfo.put("lng",orders.get(i).getLon());
                userInfo.put("lat",orders.get(i).getLat());
                orders.get(i).setUserInfo(userInfo);
            }
        }
        return orders;
    }




    @Override
    public boolean acceptOrder(Integer orderId, String acceptText) {
        order order = new order();
        order.setId(orderId);
        order.setHorsemanReceptionTime(new Date());
        order.setOrderState("进行中");
        int i = orderMapper.updateByPrimaryKeySelective(order);
        order dataOrder = orderMapper.selectByPrimaryKey(orderId);
        if (i == 1) {
            //添加消息记录
            info info = new info();
            info.setOpenid(dataOrder.getOpenId());
            info.setHorsemanOpenid(dataOrder.getHorsemanAccount());
            info.setInfoTitle("骑手接单提醒");
            info.setInfoType("订单消息");
            info.setInfoContent("骑手：" + dataOrder.getHorsemanName() + "已经接收了您的订单，骑手将在最快的时间内联系您，请保持通话畅通，耐心等待。");
            info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/horseman-icon.png");
            info.setInfoTime(new Date());

            infoMapper.insertSelective(info);

            log.debug("开始推送");
            //推送消息给骑手，提醒接单
            String userToken = gzhMapper.selectByPrimaryKey(3).getAccessToken();


            Template usertemplate = new Template();
            usertemplate.setTemplate_id("TiOHwLeEs50yt89INpyc-gXk2KnHw4qwpnUK3SiSvP4");
            usertemplate.setTouser(dataOrder.getOpenId());
            usertemplate.setPage("pages/order/main");
            List<TemplateParam> userparas = new ArrayList<TemplateParam>();
            userparas.add(new TemplateParam("name1", dataOrder.getHorsemanName()));
            userparas.add(new TemplateParam("thing4", acceptText));
            userparas.add(new TemplateParam("time8", new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(dataOrder.getHorsemanReceptionTime())));
            userparas.add(new TemplateParam("thing3", dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市") + 1, Math.min(dataOrder.getUserArea().indexOf("市") + 20, dataOrder.getUserArea().length()))));
            userparas.add(new TemplateParam("character_string6", dataOrder.getOrderNumber()));
            usertemplate.setTemplateParamList(userparas);
            String requestuserUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN";
            requestuserUrl = requestuserUrl.replace("ACCESS_TOKEN", userToken);

            net.sf.json.JSONObject jsonuserResult = CommonUtil.httpsRequest(requestuserUrl, "POST", usertemplate.toJSON());
            if (jsonuserResult != null) {
                System.out.println(jsonuserResult);
                int errorCode = jsonuserResult.getInt("errcode");
                String errorMessage = jsonuserResult.getString("errmsg");
                if (errorCode == 0) {
                    log.debug("提醒用户上门服务Send Success");
                } else {
                    log.debug("订阅消息发送失败:" + errorCode + "," + errorMessage);
                }
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public order findOneOrder(String orderId) {
        //修改骑手到达时间
        order order = new order();
        order.setId(Integer.parseInt(orderId));
        order.setHorsemanArrivalTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);

        order = orderMapper.selectByPrimaryKey(Integer.parseInt(orderId));

        orderItemExample oIEx = new orderItemExample();
        orderItemExample.Criteria criteria1 = oIEx.createCriteria();
        criteria1.andOrderIdEqualTo(Integer.parseInt(orderId));
        List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
        order.setOrderItems(orderItems);
        return order;
    }

    @Override
    public boolean abnormalOrder(Integer orderId, String explain) {
        //返回是否修改成功
        boolean isdelect = true;
        if (StringUtils.isNotBlank(ObjectUtils.toString(orderId))) {
            order order = orderMapper.selectByPrimaryKey(orderId);
            if (StringUtils.isNotBlank(ObjectUtils.toString(order.getId()))) {
                order.setOrderState("异常订单");
                order.setOrderExplain(explain);
                orderMapper.updateByPrimaryKeySelective(order);
            } else {
                isdelect = false;
                log.debug("该订单不存在");
            }
        } else {
            isdelect = false;
            log.debug("传入订单Id为空");
        }
        return isdelect;
    }

    @Override
    public boolean updateUserInfo(horseman horseman) {
        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(horseman.getOpenId());
        List<cn.itcast.pojo.horseman> horsemen = horsemanMapper.selectByExample(hEx);
        horseman.setHorsemanId(horsemen.get(0).getHorsemanId());
        int i = horsemanMapper.updateByPrimaryKeySelective(horseman);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean updateOrder(order order) {
        int i = orderMapper.updateByPrimaryKeySelective(order);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean updateOrderItem(orderItem orderItem, Integer orderId) {
        order order = new order();
        order.setOrderState("待支付");
        order.setId(orderId);
        orderMapper.updateByPrimaryKeySelective(order);
        int i = orderItemMapper.updateByPrimaryKeySelective(orderItem);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean addOrderItem(Integer orderId, Integer classifyId) {

        classsify classsify = classsifyMapper.selectByPrimaryKey(classifyId);
        //查询是否存在
        orderItemExample oEx = new orderItemExample();
        orderItemExample.Criteria criteria = oEx.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        List<orderItem> orderItems = orderItemMapper.selectByExample(oEx);
        for (int i = 0; i < orderItems.size(); i++) {
            if (classsify.getName().equals(orderItems.get(i).getProductType())) {
                return false;
            }

        }

        orderItem orderItem = new orderItem();
        orderItem.setTodayPrice(classsify.getSettlementPrice());
        orderItem.setUnit(classsify.getMeasure());
        orderItem.setProductImg(classsify.getIcon());
        orderItem.setProductType(classsify.getName());
        orderItem.setOrderId(orderId);
        int i = orderItemMapper.insertSelective(orderItem);
        order orders=new order();
        orders.setId(orderId);
        orders.setPayProductType(classsify.getName());
        if (i == 1) {
            //orderMapper.updateordertype(orders);
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean delectOrderItem(Integer orderId) {
        int i = orderItemMapper.deleteByPrimaryKey(orderId);
        if (i == 1) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public boolean createAccount(account account) {
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(account.getOpenId());
        List<cn.itcast.pojo.account> accounts = accountMapper.selectByExample(aEx);
        if (accounts.isEmpty()) {
            int i = accountMapper.insertSelective(account);
            if (i == 1) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    @Override
    public boolean toPayByOrder(Integer orderId, String openId, double price) {
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andAccountTypeidEqualTo(1);
        List<account> accounts = accountMapper.selectByExample(aEx);
        if (accounts.isEmpty()) {
            return false;
        } else {
            //查询订单金额
            order order = orderMapper.selectByPrimaryKey(orderId);
            String number = order.getOrderNumber();
            if (new BigDecimal(accounts.get(0).getAccountMoneyBalance()).compareTo(new BigDecimal(price)) < 0) {
                return false;
            } else {
                earningsExample example = new earningsExample();
                earningsExample.Criteria earningsOne = example.createCriteria();
                earningsOne.andOpenidEqualTo(order.getHorsemanAccount());
                earningsOne.andNumberEqualTo(number);
                earningsOne.andStateEqualTo("已出账");
                List<earnings> earningsList = earningsMapper.selectByExample(example);
                if(earningsList.size()==0){
                    //获取用户账户
                    accountExample userEx = new accountExample();
                    accountExample.Criteria userCriteria = userEx.createCriteria();
                    userCriteria.andOpenIdEqualTo(order.getOpenId());
                    userCriteria.andAccountTypeidEqualTo(2);
                    List<account> userAccounts = accountMapper.selectByExample(userEx);
                    userAccounts.get(0).setAccountMoneyBalance(DoubleUtils.add(userAccounts.get(0).getAccountMoneyBalance(), order.getPayOrderMoney()));
                    userAccounts.get(0).setAccountMoneyRental(DoubleUtils.add(userAccounts.get(0).getAccountMoneyRental(), order.getPayOrderMoney()));
                    userAccounts.get(0).setAccountEarningsConsume(DoubleUtils.add(userAccounts.get(0).getAccountEarningsConsume(), order.getPayOrderMoney()));
                    //修改骑手账户余额
                    log.debug("账户余额:" + accounts.get(0).getAccountMoneyBalance());
                    log.debug("订单金额:" + order.getPayOrderMoney());
                    accounts.get(0).setAccountMoneyBalance(DoubleUtils.sub(accounts.get(0).getAccountMoneyBalance(), price));
                    log.debug("支付后账户余额:" + accounts.get(0).getAccountMoneyBalance());
                    //修改用户账户余额

                    int i = accountMapper.updateByPrimaryKeySelective(accounts.get(0));
                    if (i == 1) {
                        int j = accountMapper.updateByPrimaryKeySelective(userAccounts.get(0));
                        //添加消息记录
                        info info = new info();
                        info.setOpenid(userAccounts.get(0).getOpenId());
                        info.setUserOpenid(order.getOpenId());
                        info.setInfoTitle("订单金额到账了");
                        info.setInfoType("订单消息");
                        DecimalFormat df = new DecimalFormat("######0.00"); //.00表示保留两位小数，三位小数就是三个0，以此类推
                        info.setInfoContent("您已成功完成订单，您获得" + df.format(order.getPayOrderMoney()) + "元环保佣金，快去钱包查看吧。");
                        info.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
                        info.setInfoTime(new Date());
                        infoMapper.insertSelective(info);

                        //根据订单明细中不同商品，佣金比例不同来计算金额
                        //查出订单明细
                        orderItemExample oEx = new orderItemExample();
                        orderItemExample.Criteria criteriaItem = oEx.createCriteria();
                        criteriaItem.andOrderIdEqualTo(orderId);
                        List<orderItem> orderItems = orderItemMapper.selectByExample(oEx);
                        //订单总金额
                        //一级分销金额
                        double onecount = 0.00;
                        //二级分销金额
                        double twocount = 0.00;
                        //首单奖励金额
                        double DistributionMoney = 0.00;

//                    double twoDistributionMoney = 0.00;
                        //判断用户是否首次下单
                        List<order> orderInfo = orderMapper.selectOrderStatus(order.getOpenId(), "已完成");

                        for (int it = 0; it < orderItems.size(); it++) {
                            classsifyExample cEx = new classsifyExample();
                            classsifyExample.Criteria criteriaClass = cEx.createCriteria();
                            criteriaClass.andNameEqualTo(orderItems.get(it).getProductType());
                            List<classsify> classsifies = classsifyMapper.selectByExample(cEx);
                            if (classsifies.get(0).getProfitMeasure().equals("number")) {
                                onecount = DoubleUtils.add(onecount, DoubleUtils.mul(orderItems.get(it).getSum(), Double.parseDouble(classsifies.get(0).getPreviousProfit())));
                                twocount = DoubleUtils.add(twocount, DoubleUtils.mul(orderItems.get(it).getSum(), Double.parseDouble(classsifies.get(0).getPreviousTwoProfit())));
                            } else {
                                onecount = DoubleUtils.add(onecount, DoubleUtils.mul(orderItems.get(it).getFinallyWeight(), Double.parseDouble(classsifies.get(0).getPreviousProfit())));
                                twocount = DoubleUtils.add(twocount, DoubleUtils.mul(orderItems.get(it).getFinallyWeight(), Double.parseDouble(classsifies.get(0).getPreviousTwoProfit())));
                            }
                        }
                        log.info("用户购买电子废弃类一级伙伴得到佣金：{}", onecount);
                        log.info("用户购买电子废弃类二级伙伴得到佣金：{}", twocount);
                        //一级分销伙伴
                        if (userMapper.selectByPrimaryKey(order.getOpenId()).getUserOneDistribution() != null) {
                            //用户一级分销提成
                            accountExample oneUserEx = new accountExample();
                            accountExample.Criteria oneUserCriteria = oneUserEx.createCriteria();
                            oneUserCriteria.andOpenIdEqualTo(userMapper.selectByPrimaryKey(order.getOpenId()).getUserOneDistribution());
                            oneUserCriteria.andAccountTypeidEqualTo(2);
                            List<account> oneUserAccounts = accountMapper.selectByExample(oneUserEx);

                            if (orderInfo.size() == 0) {    //首次下单
                                log.info("用户首次下单·····");
                                //判断他的一二级用户是否为环保铁骑
                                String oneOpenId = userMapper.selectByPrimaryKey(order.getOpenId()).getUserOneDistribution();

                                if (oneOpenId != null || !oneOpenId.isEmpty()) {

                                    user oneUser = userMapper.selectByPrimaryKey(oneOpenId);

                                    if (oneUser.getUserCavalry() != null) {

                                        //此用户的一级环保伙伴是否为环保铁骑

                                        if (oneUser.getUserCavalry().equals("环保铁骑")) {

                                            log.info("该用户的一级环保伙伴为环保铁骑·····");
                                            //订单重量
                                            Double CavalryMoney = 0.00;    //首单重量奖金
                                            Double device = 0.00;        //首单电器类奖金

                                            Double sumFinallyWeight = orderItemMapper.sumFinallyWeight(orderId);


                                            if (sumFinallyWeight >= 20) {    //订单重量大于20公斤以上
                                                CavalryMoney = 5.00;
                                                log.info("用户订单重量{}公斤,奖励一级推广用户({}})5.00元奖金·····", sumFinallyWeight, oneUser.getNickName());
                                            } else {                        //20公斤以下了
                                                CavalryMoney = 2.00;
                                                log.info("用户订单重量{}公斤,奖励一级推广用户({}})2.00元奖金·····", sumFinallyWeight, oneUser.getNickName());
                                            }
                                            //查看订单中是否有电子废弃物类
                                            for (int io = 0; io < orderItems.size(); io++) {
                                                classsifyExample lyy = new classsifyExample();
                                                classsifyExample.Criteria criteria1 = lyy.createCriteria();
                                                criteria1.andNameEqualTo(orderItems.get(io).getProductType());
                                                List<classsify> fid = classsifyMapper.selectByExample(lyy);

                                                if (fid.get(0).getProfitMeasure().equals("number")) {
                                                    //获取订单金额
                                                    Double sum = orderItems.get(io).getSum();
                                                    log.info("电器类订单金额：{}", sum);
                                                    device = DoubleUtils.add(device, sum);
                                                }
                                            }

                                            Double sumDevice = 0.00;

                                            //订单金额>=20元以上 奖励5元
                                            if(device >=50 ){
                                                sumDevice = 5.00;
                                                log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})5.00元奖金·····", device, oneUser.getNickName());
                                            }else if(device <10){
                                                sumDevice = 0.00;
                                                log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})0.00元奖金·····", device, oneUser.getNickName());
                                            }else {
                                                sumDevice = 2.00;
                                                log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})2.00元奖金·····", device, oneUser.getNickName());

                                            }

//                                        if (device >= 10 && device < 20) {
//                                            sumDevice = 2.00;
//                                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})2.00元奖金·····", device, oneUser.getNickName());
//                                        } else if (device >= 20 && device < 50) {
//                                            sumDevice = 5.00;
//                                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})5.00元奖金·····", device, oneUser.getNickName());
//                                        } else if (device >= 50 && device < 100) {
//                                            sumDevice = 10.00;
//                                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})10.00元奖金·····", device, oneUser.getNickName());
//                                        } else if (device >= 100 && device < 200) {
//                                            sumDevice = 15.00;
//                                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})15.00元奖金·····", device, oneUser.getNickName());
//                                        } else if (device >= 200) {
//                                            sumDevice = 20.00;
//                                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})20.00元奖金·····", device, oneUser.getNickName());
//                                        }

                                            //首单奖励总金额
                                            Double sumMoney = DoubleUtils.add(CavalryMoney, sumDevice);

                                            DistributionMoney = sumMoney;

                                            //添加一级分销首单收益记录
                                            earnings oneEar = new earnings();
                                            oneEar.setAccountId(oneUserAccounts.get(0).getAccountId());
                                            oneEar.setName(oneUserAccounts.get(0).getAccountName());
                                            oneEar.setPhone(oneUserAccounts.get(0).getAccountPhone());
                                            oneEar.setOpenid(oneUserAccounts.get(0).getOpenId());
                                            oneEar.setSource("首单奖金");
                                            oneEar.setNumber(getOrderIdByTime());
                                            oneEar.setNum(sumMoney);
                                            oneEar.setState("已到账");
                                            oneEar.setEarningsExplain("首单奖金");
                                            //生成一级分销收益记录
                                            int CavalryEarning = earningsMapper.insertSelective(oneEar);

                                            if (CavalryEarning == 1) {
                                                log.info("添加一级分销首单收益记录成功·····");
                                                //添加消息记录
                                                info infoOne = new info();
                                                infoOne.setOpenid(oneUserAccounts.get(0).getOpenId());
                                                infoOne.setUserOpenid(order.getOpenId());
                                                infoOne.setInfoTitle("一级分销首单奖金到账了");
                                                infoOne.setInfoType("订单消息");
                                                infoOne.setInfoContent("您推广的用户：" + order.getUserName() + "成功完成首次订单，您获得" + df.format(sumMoney) + "元首单奖金，快去钱包查看吧。");
                                                infoOne.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
                                                infoOne.setInfoTime(new Date());
                                                infoMapper.insertSelective(infoOne);
                                                log.info("生成消息记录成功·····");
                                            } else {
                                                log.info("添加一级分销首单收益记录失败·····");
                                            }
                                        }
                                    } else {
                                        log.info("该用户的一级推广伙伴不是环保铁骑鸭·····");
                                    }
                                }
                            }

                            oneUserAccounts.get(0).setAccountMoneyBalance(DoubleUtils.add(oneUserAccounts.get(0).getAccountMoneyBalance(), DoubleUtils.add(DistributionMoney, onecount)));
                            oneUserAccounts.get(0).setAccountMoneyRental(DoubleUtils.add(oneUserAccounts.get(0).getAccountMoneyRental(), DoubleUtils.add(DistributionMoney, onecount)));
                            oneUserAccounts.get(0).setAccountEarningsOneDistribution(DoubleUtils.add(oneUserAccounts.get(0).getAccountEarningsOneDistribution(), DoubleUtils.add(DistributionMoney, onecount)));
                            accountMapper.updateByPrimaryKeySelective(oneUserAccounts.get(0));

                            //添加一级分销收益记录
                            earnings oneEarnings = new earnings();
                            oneEarnings.setAccountId(oneUserAccounts.get(0).getAccountId());
                            oneEarnings.setName(oneUserAccounts.get(0).getAccountName());
                            oneEarnings.setPhone(oneUserAccounts.get(0).getAccountPhone());
                            oneEarnings.setOpenid(oneUserAccounts.get(0).getOpenId());
                            oneEarnings.setSource("一级分销");
                            oneEarnings.setNumber(getOrderIdByTime());
                            oneEarnings.setNum(onecount);
                            oneEarnings.setState("已到账");
                            oneEarnings.setEarningsExplain("一级分销");

                            //生成一级分销收益记录
                            int onei1 = earningsMapper.insertSelective(oneEarnings);
                            if (onei1 == 1) {
                                //添加消息记录
                                info infoone = new info();
                                infoone.setOpenid(oneUserAccounts.get(0).getOpenId());
                                infoone.setUserOpenid(order.getOpenId());
                                infoone.setInfoTitle("一级分销佣金到账了");
                                infoone.setInfoType("订单消息");
                                infoone.setInfoContent("您推广的用户：" + order.getUserName() + "成功完成订单，您获得" + df.format(onecount) + "元佣金，快去钱包查看吧。");
                                infoone.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
                                infoone.setInfoTime(new Date());

                                infoMapper.insertSelective(infoone);
                                log.debug("生成收益记录成功");
                            } else {
                                log.debug("生成收益记录失败");
                            }
                        }


                        //用户二级分销提成
                        if (userMapper.selectByPrimaryKey(order.getOpenId()).getUserTwoDistribution() != null) {
                            accountExample twoUserEx = new accountExample();
                            accountExample.Criteria twoUserCriteria = twoUserEx.createCriteria();
                            twoUserCriteria.andOpenIdEqualTo(userMapper.selectByPrimaryKey(order.getOpenId()).getUserTwoDistribution());
                            twoUserCriteria.andAccountTypeidEqualTo(2);
                            List<account> twoUserAccounts = accountMapper.selectByExample(twoUserEx);

                            twoUserAccounts.get(0).setAccountMoneyBalance(DoubleUtils.add(twoUserAccounts.get(0).getAccountMoneyBalance(), twocount));
                            twoUserAccounts.get(0).setAccountMoneyRental(DoubleUtils.add(twoUserAccounts.get(0).getAccountMoneyRental(), twocount));
                            twoUserAccounts.get(0).setAccountEarningsTwoDistribution(DoubleUtils.add(twoUserAccounts.get(0).getAccountEarningsTwoDistribution(), twocount));
                            accountMapper.updateByPrimaryKeySelective(twoUserAccounts.get(0));
                            //添加二级分销收益记录
                            earnings twoEarnings = new earnings();
                            twoEarnings.setAccountId(twoUserAccounts.get(0).getAccountId());
                            twoEarnings.setName(twoUserAccounts.get(0).getAccountName());
                            twoEarnings.setPhone(twoUserAccounts.get(0).getAccountPhone());
                            twoEarnings.setOpenid(twoUserAccounts.get(0).getOpenId());
                            twoEarnings.setSource("二级分销");
                            twoEarnings.setNumber(getOrderIdByTime());
                            twoEarnings.setNum(twocount);
                            twoEarnings.setState("已到账");
                            twoEarnings.setEarningsExplain("二级分销");

                            //生成二级分销收益记录
                            int twoi1 = earningsMapper.insertSelective(twoEarnings);
                            if (twoi1 == 1) {
                                //添加消息记录
                                info infotwo = new info();
                                infotwo.setOpenid(twoUserAccounts.get(0).getOpenId());
                                infotwo.setUserOpenid(order.getOpenId());
                                infotwo.setInfoTitle("二级分销佣金到账了");
                                infotwo.setInfoType("订单消息");
                                infotwo.setInfoContent("您的二级推广用户：" + order.getUserName() + "成功完成订单，您获得" + df.format(twocount) + "元佣金，快去钱包查看吧。");
                                infotwo.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
                                infotwo.setInfoTime(new Date());

                                infoMapper.insertSelective(infotwo);
                                log.debug("生成收益记录成功");
                            } else {
                                log.debug("生成收益记录失败");
                            }
                        }


                        //添加收益记录
                        earnings earnings = new earnings();
                        earnings.setAccountId(userAccounts.get(0).getAccountId());
                        earnings.setName(userAccounts.get(0).getAccountName());
                        earnings.setPhone(userAccounts.get(0).getAccountPhone());
                        earnings.setOpenid(userAccounts.get(0).getOpenId());
                        earnings.setSource("订单消费");
                        earnings.setNumber(getOrderIdByTime());
                        earnings.setNum(order.getPayOrderMoney());
                        earnings.setState("已到账");
                        earnings.setEarningsExplain("骑手支付订单，获取收益");

                        //生成收益记录
                        int i1 = earningsMapper.insertSelective(earnings);
                        if (i1 == 1) {
                            log.debug("生成收益记录成功");
                        } else {
                            log.debug("生成收益记录失败");
                        }

                        //骑手添加消费记录
                        earnings horearnings = new earnings();
                        horearnings.setAccountId(accounts.get(0).getAccountId());
                        horearnings.setName(accounts.get(0).getAccountName());
                        horearnings.setPhone(accounts.get(0).getAccountPhone());
                        horearnings.setOpenid(accounts.get(0).getOpenId());
                        horearnings.setSource("骑手支付");
                        horearnings.setNumber(number);
                        horearnings.setNum(price);
                        horearnings.setState("已出账");
                        horearnings.setEarningsExplain("骑手支付订单，骑手支出");

                        //生成收益记录
                        int ihor = earningsMapper.insertSelective(horearnings);
                        if (ihor == 1) {
                            log.debug("骑手生成收益记录成功");
                        } else {
                            log.debug("骑手生成收益记录失败");
                        }

                        //更新订单
                        order.setOrderState("已完成");
                        order.setPayTime(new Date());
                        orderMapper.updateByPrimaryKeySelective(order);
                        return true;
                    } else {
                        log.debug("账户金额修改失败");
                        return false;
                    }
                }else{
                    log.info("骑手已经支付过了啊啊啊");
                    return false;
                }
            }
        }
    }



    /**
     * 功能描述: <br>
     * 〈骑手支付模块〉
     * @Author: lyy
     * @Date: 2020/8/11 15:56
     * @Param: [orderId, openId, price]
     * @Return: cn.itcast.util.ResponseEntity
     */
    @Override
    public ResponseEntity PayByOrderLu(Integer orderId, String openId, double price) {


        if(orderId==null && orderId==0) return new ResponseEntity(300,"参数orderId不能为空");
        if(openId.isEmpty()) return new ResponseEntity(300,"参数openId不能为空");
        //if(price == 0 && price == 0.00) return new ResponseEntity(300,"参数price不能为空或者price不能为0");

        //获取订单数据
        order order = orderMapper.selectByPrimaryKey(orderId);
        log.info("order数据:{}",order.toString());

        //订单编号
        String orderNumber = order.getOrderNumber();

        //判断骑手是否有足够金额支付
        accountExample aEx = new accountExample();
        accountExample.Criteria criteria = aEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andAccountTypeidEqualTo(1);
        List<account> horsemanAccounts = accountMapper.selectByExample(aEx);
        log.info("骑手账户数据:{}",horsemanAccounts.get(0));

        if(horsemanAccounts.isEmpty()) return new ResponseEntity(401,"骑手账户数据为空");

        earningsExample judgeHorsemanExample = new earningsExample();
        earningsExample.Criteria earningsJudge = judgeHorsemanExample.createCriteria();
        earningsJudge.andOpenidEqualTo(order.getHorsemanAccount());
        earningsJudge.andNumberEqualTo(orderNumber);
        earningsJudge.andStateEqualTo("已出账");
        List<earnings> earningsList = earningsMapper.selectByExample(judgeHorsemanExample);

        //判断是否有余额支付
        if (new BigDecimal(horsemanAccounts.get(0).getAccountMoneyBalance()).compareTo(new BigDecimal(price)) < 0) return new ResponseEntity(666,"余额不足支付！！！");

        earningsExample judgeUserExample = new earningsExample();
        earningsExample.Criteria earningsJudgeUser = judgeUserExample.createCriteria();
        earningsJudgeUser.andOpenidEqualTo(order.getOpenId());
        earningsJudgeUser.andNumberEqualTo(orderNumber);

        earningsJudgeUser.andStateEqualTo("已到账");
        List<earnings> earningsListUser = earningsMapper.selectByExample(judgeUserExample);

        //判断订单是否已经支付过
        if(!earningsList.isEmpty() && earningsList.size()!=0) return new ResponseEntity(400,"该订单已经支付过了");
        if(!earningsListUser.isEmpty() && earningsListUser.size()!=0) return new ResponseEntity(400,"该订单已经支付过了");

        //获取用户账户
        accountExample userExample = new accountExample();
        accountExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andOpenIdEqualTo(order.getOpenId());
        userCriteria.andAccountTypeidEqualTo(2);
        List<account> userAccounts = accountMapper.selectByExample(userExample);

        if(userAccounts.isEmpty()) return new ResponseEntity(404,"用户账户信息为空");

        log.info("userAccounts用户账户信息数据：{}",userAccounts.get(0));
        //修改用户账户余额
        userAccounts.get(0).setAccountMoneyBalance(DoubleUtils.add(userAccounts.get(0).getAccountMoneyBalance(), order.getPayOrderMoney()));
        userAccounts.get(0).setAccountMoneyRental(DoubleUtils.add(userAccounts.get(0).getAccountMoneyRental(), order.getPayOrderMoney()));
        userAccounts.get(0).setAccountEarningsConsume(DoubleUtils.add(userAccounts.get(0).getAccountEarningsConsume(), order.getPayOrderMoney()));

        log.info("骑手账户金额:{}",horsemanAccounts.get(0).getAccountMoneyBalance());
        log.info("订单金额：{}",order.getPayOrderMoney());
        log.info("骑手需要订单金额：{}",price);
        //修改骑手账户余额
        horsemanAccounts.get(0).setAccountMoneyBalance(DoubleUtils.sub(horsemanAccounts.get(0).getAccountMoneyBalance(), price));
        log.info("骑手支付订单后账户余额为：{}",horsemanAccounts.get(0).getAccountMoneyBalance());

        //修改用户账户余额
        int userAccountMoney = accountMapper.updateByPrimaryKeySelective(userAccounts.get(0));
        if(userAccountMoney==0)return new ResponseEntity(402,"修改用户账户余额失败！！！");

        //修改骑手账户余额
        int horsemanAccountMoney = accountMapper.updateByPrimaryKeySelective(horsemanAccounts.get(0));
        if(horsemanAccountMoney==0) return new ResponseEntity(403,"修改骑手账户余额失败！！！");

        //添加用户收益记录
        earnings userEarnings = new earnings();
        userEarnings.setAccountId(userAccounts.get(0).getAccountId());
        userEarnings.setName(userAccounts.get(0).getAccountName());
        userEarnings.setOpenid(userAccounts.get(0).getOpenId());
        userEarnings.setSource("订单消费");
        userEarnings.setNumber(orderNumber);
        userEarnings.setNum(order.getPayOrderMoney());
        userEarnings.setState("已到账");
        userEarnings.setEarningsExplain("骑手支付订单，获取收益");

        int userEarningsOne = earningsMapper.insertSelective(userEarnings);
        if(userEarningsOne == 0) return new ResponseEntity(500,"用户收益记录生成失败");

        //添加骑手消费记录
        earnings horsemanEarnings = new earnings();
        horsemanEarnings.setAccountId(horsemanAccounts.get(0).getAccountId());
        horsemanEarnings.setName(horsemanAccounts.get(0).getAccountName());
        horsemanEarnings.setOpenid(horsemanAccounts.get(0).getOpenId());
        horsemanEarnings.setSource("骑手支付");
        horsemanEarnings.setNumber(orderNumber);
        horsemanEarnings.setNum(price);
        horsemanEarnings.setState("已出账");
        horsemanEarnings.setEarningsExplain("骑手支付订单，骑手支出");

        int horsemanEarningsOne = earningsMapper.insertSelective(horsemanEarnings);
        if(horsemanEarningsOne == 0) return new ResponseEntity(505,"骑手收益记录生成失败");

        //添加消息记录
        info userInfo = new info();
        userInfo.setOpenid(userAccounts.get(0).getOpenId());
        userInfo.setUserOpenid(order.getOpenId());
        userInfo.setInfoTitle("订单金额到账了");
        userInfo.setInfoType("订单消息");
        DecimalFormat df = new DecimalFormat("######0.00"); //.00表示保留两位小数，三位小数就是三个0，以此类推
        userInfo.setInfoContent("您已成功完成订单，您获得" + df.format(order.getPayOrderMoney()) + "元环保佣金，快去钱包查看吧。");
        userInfo.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
        userInfo.setInfoTime(new Date());
        infoMapper.insertSelective(userInfo);

        //根据订单明细中不同商品，佣金比例不同来计算金额
        //查出订单明细
        orderItemExample oEx = new orderItemExample();
        orderItemExample.Criteria criteriaItem = oEx.createCriteria();
        criteriaItem.andOrderIdEqualTo(orderId);
        List<orderItem> orderItems = orderItemMapper.selectByExample(oEx);
        //订单总金额
        //一级分销金额
        double onecount = 0.00;
        //二级分销金额
        double twocount = 0.00;
        //首单奖励金额
        double DistributionMoney = 0.00;

        for (int it = 0; it < orderItems.size(); it++) {
            classsifyExample cEx = new classsifyExample();
            classsifyExample.Criteria criteriaClass = cEx.createCriteria();
            criteriaClass.andNameEqualTo(orderItems.get(it).getProductType());
            List<classsify> classsifies = classsifyMapper.selectByExample(cEx);
            if (classsifies.get(0).getProfitMeasure().equals("number")) {
                onecount = DoubleUtils.add(onecount, DoubleUtils.mul(orderItems.get(it).getSum(), Double.parseDouble(classsifies.get(0).getPreviousProfit())));
                twocount = DoubleUtils.add(twocount, DoubleUtils.mul(orderItems.get(it).getSum(), Double.parseDouble(classsifies.get(0).getPreviousTwoProfit())));
            } else {
                onecount = DoubleUtils.add(onecount, DoubleUtils.mul(orderItems.get(it).getFinallyWeight(), Double.parseDouble(classsifies.get(0).getPreviousProfit())));
                twocount = DoubleUtils.add(twocount, DoubleUtils.mul(orderItems.get(it).getFinallyWeight(), Double.parseDouble(classsifies.get(0).getPreviousTwoProfit())));
            }
        }

        log.info("用户购买电子废弃类一级伙伴得到佣金：{}", onecount);
        log.info("用户购买电子废弃类二级伙伴得到佣金：{}", twocount);

        //判断用户是否首次下单
        List<order> orderInfo = orderMapper.selectOrderStatus(order.getOpenId(), "已完成");

        //一级分销用户openId
        String oneOpenId = userMapper.selectByPrimaryKey(order.getOpenId()).getUserOneDistribution();

        //二级分销用户openId
        String twoOpenId = userMapper.selectByPrimaryKey(order.getOpenId()).getUserTwoDistribution();

        //一级分销伙伴
        if (oneOpenId != null && !oneOpenId.isEmpty()) {
            //用户一级分销提成
            accountExample oneUserEx = new accountExample();
            accountExample.Criteria oneUserCriteria = oneUserEx.createCriteria();
            oneUserCriteria.andOpenIdEqualTo(userMapper.selectByPrimaryKey(order.getOpenId()).getUserOneDistribution());
            oneUserCriteria.andAccountTypeidEqualTo(2);
            List<account> oneUserAccounts = accountMapper.selectByExample(oneUserEx);
            if(orderInfo.size() == 0){   //首次下单
                log.info("用户首次下单·····");
                //一级分销伙伴资料
                user oneUser = userMapper.selectByPrimaryKey(oneOpenId);

                log.info("一级分销伙伴资料：{}",oneUser);

                if(oneUser.getUserCavalry()!=null){

                    //判断一级用户是否为环保铁骑
                    if(oneUser.getUserCavalry().equals("环保铁骑")){

                        log.info("该用户的一级环保伙伴为环保铁骑·····");

                        //订单重量
                        Double CavalryMoney = 0.00;    //首单重量奖金
                        Double device = 0.00;        //首单电器类奖金
                        Double sumFinallyWeight = orderItemMapper.sumFinallyWeight(orderId);

                        if (sumFinallyWeight >= 20) {    //订单重量大于20公斤以上
                            CavalryMoney = 5.00;
                            log.info("用户订单重量{}公斤,奖励一级推广用户({}})5.00元奖金·····", sumFinallyWeight, oneUser.getNickName());
                        } else {                        //20公斤以下了
                            CavalryMoney = 2.00;
                            log.info("用户订单重量{}公斤,奖励一级推广用户({}})2.00元奖金·····", sumFinallyWeight, oneUser.getNickName());
                        }

                        //查看订单中是否有电子废弃物类
                        for (int io = 0; io < orderItems.size(); io++) {
                            classsifyExample lyy = new classsifyExample();
                            classsifyExample.Criteria criteria1 = lyy.createCriteria();
                            criteria1.andNameEqualTo(orderItems.get(io).getProductType());
                            List<classsify> fid = classsifyMapper.selectByExample(lyy);

                            if (fid.get(0).getProfitMeasure().equals("number")) {
                                //获取订单金额
                                Double sum = orderItems.get(io).getSum();
                                log.info("电器类订单金额：{}", sum);
                                device = DoubleUtils.add(device, sum);
                            }
                        }

                        Double sumDevice = 0.00;

                        //订单金额>=20元以上 奖励5元
                        if(device >=50 ){
                            sumDevice = 5.00;
                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})5.00元奖金·····", device, oneUser.getNickName());
                        }else if(device <10){
                            sumDevice = 0.00;
                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})0.00元奖金·····", device, oneUser.getNickName());
                        }else {
                            sumDevice = 2.00;
                            log.info("用户订单电子废弃物类总价格{},奖励一级推广用户({})2.00元奖金·····", device, oneUser.getNickName());

                        }

                        //首单奖励总金额
                        Double sumMoney = DoubleUtils.add(CavalryMoney, sumDevice);

                        DistributionMoney = sumMoney;

                        //添加一级分销首单收益记录

                        earnings oneEar = new earnings();
                        oneEar.setAccountId(oneUserAccounts.get(0).getAccountId());
                        oneEar.setName(oneUserAccounts.get(0).getAccountName());
                        oneEar.setPhone(oneUserAccounts.get(0).getAccountPhone());
                        oneEar.setOpenid(oneUserAccounts.get(0).getOpenId());
                        oneEar.setSource("首单奖金");
                        oneEar.setNumber(getOrderIdByTime());
                        oneEar.setNum(sumMoney);
                        oneEar.setState("已到账");
                        oneEar.setEarningsExplain("首单奖金");
                        //生成一级分销收益记录
                        int CavalryEarning = earningsMapper.insertSelective(oneEar);

                        if (CavalryEarning == 1) {
                            log.info("添加一级分销首单收益记录成功·····");
                            //添加消息记录
                            info infoOne = new info();
                            infoOne.setOpenid(oneUserAccounts.get(0).getOpenId());
                            infoOne.setUserOpenid(order.getOpenId());
                            infoOne.setInfoTitle("一级分销首单奖金到账了");
                            infoOne.setInfoType("订单消息");
                            infoOne.setInfoContent("您推广的用户：" + order.getUserName() + "成功完成首次订单，您获得" + df.format(sumMoney) + "元首单奖金，快去钱包查看吧。");
                            infoOne.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
                            infoOne.setInfoTime(new Date());
                            infoMapper.insertSelective(infoOne);
                            log.info("添加一级分销首单收益记录成功·····");
                        } else {
                            log.info("添加一级分销首单收益记录失败·····");
                        }
                    }
                }


            }else{
                log.info("用户不是首次下单喔！！！");
            }

            oneUserAccounts.get(0).setAccountMoneyBalance(DoubleUtils.add(oneUserAccounts.get(0).getAccountMoneyBalance(), DoubleUtils.add(DistributionMoney, onecount)));
            oneUserAccounts.get(0).setAccountMoneyRental(DoubleUtils.add(oneUserAccounts.get(0).getAccountMoneyRental(), DoubleUtils.add(DistributionMoney, onecount)));
            oneUserAccounts.get(0).setAccountEarningsOneDistribution(DoubleUtils.add(oneUserAccounts.get(0).getAccountEarningsOneDistribution(), DoubleUtils.add(DistributionMoney, onecount)));
            accountMapper.updateByPrimaryKeySelective(oneUserAccounts.get(0));

            //添加一级分销收益记录
            earnings oneEarnings = new earnings();
            oneEarnings.setAccountId(oneUserAccounts.get(0).getAccountId());
            oneEarnings.setName(oneUserAccounts.get(0).getAccountName());
            oneEarnings.setPhone(oneUserAccounts.get(0).getAccountPhone());
            oneEarnings.setOpenid(oneUserAccounts.get(0).getOpenId());
            oneEarnings.setSource("一级分销");
            oneEarnings.setNumber(getOrderIdByTime());
            oneEarnings.setNum(onecount);
            oneEarnings.setState("已到账");
            oneEarnings.setEarningsExplain("一级分销");

            //生成一级分销收益记录
            int onei1 = earningsMapper.insertSelective(oneEarnings);
            if (onei1 == 1) {
                //添加消息记录
                info infoone = new info();
                infoone.setOpenid(oneUserAccounts.get(0).getOpenId());
                infoone.setUserOpenid(order.getOpenId());
                infoone.setInfoTitle("一级分销佣金到账了");
                infoone.setInfoType("订单消息");
                infoone.setInfoContent("您推广的用户：" + order.getUserName() + "成功完成订单，您获得" + df.format(onecount) + "元佣金，快去钱包查看吧。");
                infoone.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
                infoone.setInfoTime(new Date());

                infoMapper.insertSelective(infoone);
                log.debug("生成收益记录成功");
            } else {
                log.debug("生成收益记录失败");
            }
        }

        //二级分销伙伴
        if (twoOpenId != null && !twoOpenId.isEmpty()) {

            accountExample twoUserEx = new accountExample();
            accountExample.Criteria twoUserCriteria = twoUserEx.createCriteria();
            twoUserCriteria.andOpenIdEqualTo(userMapper.selectByPrimaryKey(order.getOpenId()).getUserTwoDistribution());
            twoUserCriteria.andAccountTypeidEqualTo(2);
            List<account> twoUserAccounts = accountMapper.selectByExample(twoUserEx);

            twoUserAccounts.get(0).setAccountMoneyBalance(DoubleUtils.add(twoUserAccounts.get(0).getAccountMoneyBalance(), twocount));
            twoUserAccounts.get(0).setAccountMoneyRental(DoubleUtils.add(twoUserAccounts.get(0).getAccountMoneyRental(), twocount));
            twoUserAccounts.get(0).setAccountEarningsTwoDistribution(DoubleUtils.add(twoUserAccounts.get(0).getAccountEarningsTwoDistribution(), twocount));
            accountMapper.updateByPrimaryKeySelective(twoUserAccounts.get(0));
            //添加二级分销收益记录
            earnings twoEarnings = new earnings();
            twoEarnings.setAccountId(twoUserAccounts.get(0).getAccountId());
            twoEarnings.setName(twoUserAccounts.get(0).getAccountName());
            twoEarnings.setPhone(twoUserAccounts.get(0).getAccountPhone());
            twoEarnings.setOpenid(twoUserAccounts.get(0).getOpenId());
            twoEarnings.setSource("二级分销");
            twoEarnings.setNumber(getOrderIdByTime());
            twoEarnings.setNum(twocount);
            twoEarnings.setState("已到账");
            twoEarnings.setEarningsExplain("二级分销");

            //生成二级分销收益记录
            int twoi1 = earningsMapper.insertSelective(twoEarnings);
            if (twoi1 == 1) {
                //添加消息记录
                info infotwo = new info();
                infotwo.setOpenid(twoUserAccounts.get(0).getOpenId());
                infotwo.setUserOpenid(order.getOpenId());
                infotwo.setInfoTitle("二级分销佣金到账了");
                infotwo.setInfoType("订单消息");
                infotwo.setInfoContent("您的二级推广用户：" + order.getUserName() + "成功完成订单，您获得" + df.format(twocount) + "元佣金，快去钱包查看吧。");
                infotwo.setInfoImg("https://www.dhnep.cn:8181/dhn/icon/distribution-icon.png");
                infotwo.setInfoTime(new Date());

                infoMapper.insertSelective(infotwo);
                log.debug("生成收益记录成功");
            } else {
                log.debug("生成收益记录失败");
            }
        }

        //更新订单
        order.setOrderState("已完成");
        order.setPayTime(new Date());
        int orderState = orderMapper.updateByPrimaryKeySelective(order);

        if (orderState == 1){
            return new ResponseEntity(200,"订单支付成功！！！");
        }else{
            return new ResponseEntity(205,"订单支付更新失败！！！");
        }

    }

    /**
     *
     * @Description:
     * 随机生成订单号
     * @auther: 欧阳辉
     * @date: 8:23 2020/3/17
     * @param: []
     * @return: java.lang.String
     *
     */
    public String getOrderIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }


    @Override
    public horseman findUserInfo(String openId) {
        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<horseman> horsemen = horsemanMapper.selectByExample(hEx);
        if (horsemen.isEmpty()) {
            return null;
        } else {
            return horsemen.get(0);
        }

    }

    @Override
    public boolean toLatAndLon(String lat, String lon, String openId) {
        horseman horseman = new horseman();
        horseman.setHorsemanLat(lat);
        horseman.setHorsemanLon(lon);
        horseman.setOpenId(openId);
        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        int i = horsemanMapper.updateByExampleSelective(horseman, hEx);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }


    @Override
    public boolean addImgPath(String path, Integer id) {
        orderItem orderItem = orderItemMapper.selectByPrimaryKey(id);
        orderItem.setItemImg(orderItem.getItemImg() + ',' + path);
        int i = orderItemMapper.updateByPrimaryKeySelective(orderItem);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }


    @Override
    public horseman findHoresmanArea(String openId) {
        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        List<horseman> horsemen = horsemanMapper.selectByExample(hEx);
        if (horsemen.isEmpty()) {
            return null;
        } else {
            return horsemen.get(0);
        }

    }

    @Override
    public boolean cancelOrder(Integer orderId) {
        order order = new order();
        order.setId(orderId);
        order.setOrderState("待派单");
        int i = orderMapper.updateByPrimaryKeySelective(order);
        order dataOrder = orderMapper.selectByPrimaryKey(order.getId());
        if (i == 1) {

            log.debug("开始推送");
            //推送消息给管理员，提醒派单

            //1，配置
            WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
            wxStorage.setAppId("wx8153b9b18ebfa8eb");
            wxStorage.setSecret("c8bf9f0c564f7f44a297054995e6eada");
            String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
            wxStorage.setAccessToken(token);

            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxStorage);


            // 主要是这里， 设置小程序的appid和转发的页面
//            TreeMap<String, String> miniprograms = new TreeMap<String, String>();
//            miniprograms.put("appid","小程序的appid");
//            miniprograms.put("pagepath","pages/index/index?temp=1");// 注意，这里是支持传参的！！！
            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setAppid("wx51d55df222d9901e");
            miniProgram.setPagePath("pages/sendOrder/main?id=" + dataOrder.getId());
            //2,推送消息
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser("oFPgIwycQbNOq94eE40ZOH-AY98Y")//要推送的用户openid
                    .templateId("Xc_tnHReR3n1X91cwATTFitTJwgKDGn2YRhpygiA53U")//模版id
                    .url("https://www.baidu.com")
                    .build();
            templateMessage.setMiniProgram(miniProgram);
            //3,如果是正式版发送模版消息，这里需要配置你的信息
            templateMessage.addData(new WxMpTemplateData("first", "派单提醒", "#FF00FF"));
            templateMessage.addData(new WxMpTemplateData("keyword1", "有用户下单了，请及时派单", "#FF00FF"));
            templateMessage.addData(new WxMpTemplateData("keyword2", dataOrder.getUserName(), "#FF00FF"));
            templateMessage.addData(new WxMpTemplateData("keyword4", dataOrder.getUserPhone(), "#FF00FF"));
            templateMessage.addData(new WxMpTemplateData("keyword5", dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市") + 1, Math.min(dataOrder.getUserArea().indexOf("市") + 20, dataOrder.getUserArea().length())), "#FF00FF"));
            templateMessage.addData(new WxMpTemplateData("remark", "点击派单", "#FF00FF"));
            //templateMessage.addData(new WxMpTemplateData("name2", value2, color2));
            try {
                wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
            } catch (Exception e) {
                System.out.println("推送失败：" + e.getMessage());
                e.printStackTrace();
            }

            return true;
        } else {
            return false;
        }

    }

    @Override
    public List<merchant> getAllMerchant(Integer pageNum, Integer pageSize, String select, String value) {

        //分页
        PageHelper.startPage(pageNum, pageSize);
        merchantExample hEx = new merchantExample();
        cn.itcast.pojo.merchantExample.Criteria criteria = hEx.createCriteria();
        switch (select) {
            case "merchantName":
                criteria.andMerchantNameLike("%" + value + "%");
                break;
            case "merchantNumber":
                criteria.andMerchantNumberLike("%" + value + "%");
                break;
            case "merchantPhone":
                criteria.andMerchantPhoneLike("%" + value + "%");
                break;
            case "merchantIdNumber":
                criteria.andMerchantIdNumberLike("%" + value + "%");
                break;
        }
        criteria.andMerchantFidEqualTo(0);

        return merchantMapper.selectByExample(hEx);
    }


    @Override
    public List<merchant> selectAllIsopenMerchant(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return merchantMapper.selectAllIsopenMerchant();
    }



    @Override
    public boolean packgeOrder(String horesmanOpenId, String merchantOpenId, String[] ids, String name) {
        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(horesmanOpenId);
        List<horseman> horsemen = horsemanMapper.selectByExample(hEx);
        ArrayList<Integer> itemIds = new ArrayList<>();
        String oldIds = "";
        for (String id : ids) {
            itemIds.add(Integer.parseInt(id));
            oldIds = oldIds + id + ",";
        }
        log.debug(itemIds.toString());
        List<orderItem> orderItems = orderItemMapper.packageOrder(itemIds);

        packageOrder packageOrder = new packageOrder();
        packageOrder.setOpenId(horesmanOpenId);
        packageOrder.setHorsemanName(horsemen.get(0).getHorsemanName());
        //商户信息
        merchantExample mEx = new merchantExample();
        merchantExample.Criteria criteriamer = mEx.createCriteria();
        criteriamer.andOpenIdEqualTo(merchantOpenId);
        List<merchant> merchants = merchantMapper.selectByExample(mEx);
        packageOrder.setRecycleNumber(merchants.get(0).getMerchantNumber());
        packageOrder.setRecycleName(merchants.get(0).getMerchantName());
        //存旧订单明细

        packageOrder.setOldIds(oldIds);
        //订单类名
        String productNames = "";
        //订单总金额
        double productSum = 0.00;
        for (orderItem orderItem : orderItems) {
            productNames = productNames + orderItem.getProductType() + ",";
            productSum = DoubleUtils.add(productSum, orderItem.getTotalSum());
        }
        packageOrder.setProductType(productNames);
        packageOrder.setOrderSumHorseman(productSum);
        packageOrder.setOrderNumber(getOrderIdByTime());
        packageOrder.setOrderTime(new Date());

        int i = packageOrderMapper.insertSelective(packageOrder);
        if (i == 1) {

            for (orderItem orderItem : orderItems) {
                //打包订单详细
                packageOrderItem packageOrderItem = new packageOrderItem();
                //封装订单详细
                packageOrderItem.setOrderId(packageOrder.getId());

                packageOrderItem.setProductType(orderItem.getProductType());
                packageOrderItem.setProductIcon(orderItem.getProductImg());
                packageOrderItem.setAmount(orderItem.getTotalAmount());
                packageOrderItem.setFinallyWeigh(orderItem.getTotalWeight());
                packageOrderItem.setMeasure(orderItem.getUnit());
                packageOrderItem.setSumHorseman(orderItem.getTotalSum());
                packageOrderItemMapper.insertSelective(packageOrderItem);
            }
            for (Integer itemId : itemIds) {
                orderItem orderItem = orderItemMapper.selectByPrimaryKey(itemId);
                orderItem.setStatus("已打包");
                orderItemMapper.updateByPrimaryKeySelective(orderItem);

                //如果详细订单全部打包，订单状态改为
                orderItemExample oEx = new orderItemExample();
                orderItemExample.Criteria criteria1 = oEx.createCriteria();
                criteria1.andOrderIdEqualTo(orderItem.getOrderId());
                criteria1.andStatusEqualTo("未打包");
                List<cn.itcast.pojo.orderItem> orderItems1 = orderItemMapper.selectByExample(oEx);
                if (orderItems1.isEmpty()) {
                    order order = new order();
                    order.setId(orderItem.getOrderId());
                    order.setOrderState("已打包");
                    orderMapper.updateByPrimaryKeySelective(order);
                }
            }
            return true;
        } else {
            return false;
        }
    }


    @Override
    public List<String> findPackageType(String openId) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andHorsemanAccountEqualTo(openId);
        List<String> values = new ArrayList<>();
        values.add("已完成");
        values.add("已评价");
        criteria.andOrderStateIn(values);

        Map<String, List<orderItem>> orderMap = new HashMap<>();

        List<order> orders = orderMapper.selectByExample(oEx);
        List<String> productTypeList = new ArrayList<>();
        for (cn.itcast.pojo.order order : orders) {
            orderItemExample oIEx = new orderItemExample();
            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(order.getId());
            criteria1.andStatusEqualTo("未打包");
            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
            order.setOrderItems(orderItems);

            for (orderItem orderItem : orderItems) {
                if (orderMap.containsKey(orderItem.getProductType())) {
                    List<orderItem> orderItemList = orderMap.get(orderItem.getProductType());
                    orderItemList.add(orderItem);
                    orderMap.put(orderItem.getProductType(), orderItemList);
                } else {
                    List<orderItem> orderItemList = new ArrayList<>();
                    orderItemList.add(orderItem);
                    orderMap.put(orderItem.getProductType(), orderItemList);
                    productTypeList.add(orderItem.getProductType());
                }
            }
        }
        return productTypeList;
    }

    @Override
    public List<order> findPackageOrder(String openId, String type) {
        orderExample oEx = new orderExample();
        orderExample.Criteria criteria = oEx.createCriteria();
        criteria.andHorsemanAccountEqualTo(openId);
        List<String> values = new ArrayList<>();
        values.add("已完成");
        values.add("已评价");
        criteria.andOrderStateIn(values);

        Map<String, List<orderItem>> orderMap = new HashMap<>();

        List<order> orders = orderMapper.selectByExample(oEx);
        for (cn.itcast.pojo.order order : orders) {
            orderItemExample oIEx = new orderItemExample();
            orderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(order.getId());
            criteria1.andStatusEqualTo("未打包");
            criteria1.andProductTypeEqualTo(type);
            List<orderItem> orderItems = orderItemMapper.selectByExample(oIEx);
            order.setOrderItems(orderItems);
        }
        return orders;
    }

    @Override
    public List<packageOrder> findAllPackageOrder(String status, String openId) {
        packageOrderExample oEx = new packageOrderExample();
        if (status.equals("已完成")){
            oEx.setOrderByClause("pay_time DESC");
        }
        if (status.equals("待支付")){
            oEx.setOrderByClause("clear_time DESC");
        }
        if (status.equals("异常订单")){
            oEx.setOrderByClause("order_time DESC");
        }

        packageOrderExample.Criteria criteria = oEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        criteria.andStatusEqualTo(status);
        List<packageOrder> packageOrders = packageOrderMapper.selectByExample(oEx);
        for (cn.itcast.pojo.packageOrder packageOrder : packageOrders) {
            packageOrderItemExample oIEx = new packageOrderItemExample();
            packageOrderItemExample.Criteria criteria1 = oIEx.createCriteria();
            criteria1.andOrderIdEqualTo(packageOrder.getId());
            List<packageOrderItem> packageOrderItems = packageOrderItemMapper.selectByExample(oIEx);
            packageOrder.setPackageOrderItems(packageOrderItems);
        }
        return packageOrders;
    }


    @Override
    public boolean cancelPackageOrder(Integer orderId) {
        packageOrder packageOrder = packageOrderMapper.selectByPrimaryKey(orderId);
        String oldIds = packageOrder.getOldIds();
        if (!oldIds.equals("线下订单")) {
            for (String s : oldIds.split(",")) {
                orderItem orderItem = new orderItem();
                orderItem.setId(Integer.parseInt(s));
                orderItem.setStatus("未打包");
                orderItemMapper.updateByPrimaryKeySelective(orderItem);
                order order = new order();
                order.setId(orderItemMapper.selectByPrimaryKey(Integer.parseInt(s)).getOrderId());
                order.setOrderState("已完成");
                orderMapper.updateByPrimaryKeySelective(order);
            }
        }
        packageOrder.setStatus("异常订单");
        int i = packageOrderMapper.updateByPrimaryKeySelective(packageOrder);
        return i == 1;


    }


    /**
     *
     * @Description:
     * 生成订单
     * @auther: 欧阳辉
     * @date: 9:02 2020/3/17
     * @param: [order]
     * @return: boolean
     *
     */
    @Override
    public boolean addOrder(packageOrder packageOrder, String productId) {
        String[] id = productId.split(",");
        log.debug(id[0]);

        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(packageOrder.getOpenId());
        horseman horseman = horsemanMapper.selectByExample(hEx).get(0);
        packageOrder.setHorsemanName(horseman.getHorsemanName());
//		merchantExample mEx = new merchantExample();
//		merchantExample.Criteria criteriamer = mEx.createCriteria();
//		criteriamer.andMerchantNumberEqualTo(horseman.getHorsemanReferrer());
//		merchant merchant = merchantMapper.selectByExample(mEx).get(0);
//		packageOrder.setRecycleAddress(merchant.getMerchantArea());
//		packageOrder.setRecycleNumber(horseman.getHorsemanReferrer());
//		packageOrder.setRecycleName(merchant.getMerchantName());

        int in = packageOrderMapper.insertSelective(packageOrder);
        for (String s : id) {
            packageClassify packageClassify = packageClassifyMapper.selectByPrimaryKey(Integer.parseInt(s));
            packageOrderItem packageOrderItem = new packageOrderItem();
            packageOrderItem.setOrderId(packageOrder.getId());
            packageOrderItem.setProductType(packageClassify.getName());
            packageOrderItem.setProductIcon(packageClassify.getIcon());
            packageOrderItem.setMeasure("kg");
            packageOrderItemMapper.insertSelective(packageOrderItem);
        }
        return in == 1;
    }

    /**
     *
     * @Description:
     * 生成订单
     * @auther: 欧阳辉
     * @date: 9:02 2020/3/17
     * @param: [order]
     * @return: boolean
     *
     */
    @Override
    public boolean merchaaddOrder(packageOrder packageOrder, String productId) {
        String[] id = productId.split(",");
        log.debug(id[0]);

        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(packageOrder.getOpenId());
        horseman horseman = horsemanMapper.selectByExample(hEx).get(0);
        if(horseman.getHorsemanName()==null){
            packageOrder.setHorsemanName("oTIga47Szl938-xHNV1g-thRlvDM");
        }
        packageOrder.setHorsemanName(horseman.getHorsemanName());
//		merchantExample mEx = new merchantExample();
//		merchantExample.Criteria criteriamer = mEx.createCriteria();
//		criteriamer.andMerchantNumberEqualTo(horseman.getHorsemanReferrer());
//		merchant merchant = merchantMapper.selectByExample(mEx).get(0);
//		packageOrder.setRecycleAddress(merchant.getMerchantArea());
//		packageOrder.setRecycleNumber(horseman.getHorsemanReferrer());
//		packageOrder.setRecycleName(merchant.getMerchantName());

        int in = packageOrderMapper.insertSelective(packageOrder);
        for (String s : id) {
            packageClassify packageClassify = packageClassifyMapper.selectByPrimaryKey(Integer.parseInt(s));
            packageOrderItem packageOrderItem = new packageOrderItem();
            packageOrderItem.setOrderId(packageOrder.getId());
            packageOrderItem.setProductType(packageClassify.getName());
            packageOrderItem.setProductIcon(packageClassify.getIcon());
            packageOrderItem.setMeasure("kg");
            packageOrderItemMapper.insertSelective(packageOrderItem);
        }
        return in == 1;
    }



    @Override
    public Map<String, List<earnings>> findAllEarnings(String openId) {
        Map<String, List<earnings>> earningsMap = new HashMap<>();
        earningsExample eEx = new earningsExample();
        earningsExample.Criteria criteria = eEx.createCriteria();
        criteria.andOpenidEqualTo(openId);
        criteria.andSourceEqualTo("骑手支付");
        List<earnings> outEarnings = earningsMapper.selectByExample(eEx);;
        Collections.reverse(outEarnings);
        earningsMap.put("out",outEarnings);

        earningsExample oneeEx = new earningsExample();
        earningsExample.Criteria onecriteria = oneeEx.createCriteria();
        onecriteria.andOpenidEqualTo(openId);
        onecriteria.andSourceEqualTo("回收资金");
        List<earnings> inEarnings = earningsMapper.selectByExample(oneeEx);
        Collections.reverse(inEarnings);
        earningsMap.put("in",inEarnings);


        return earningsMap;

    }

    @Override
    public horseman findHoresmanStarLever(String openId) {
        horsemanExample hEx = new horsemanExample();
        horsemanExample.Criteria criteria = hEx.createCriteria();
        criteria.andOpenIdEqualTo(openId);
        return horsemanMapper.selectByExample(hEx).get(0);
    }

    @Override
    public boolean applyAdd(String openId, String orderId) {
        order order = new order();
        order.setId(Integer.parseInt(orderId));
        order.setOrderState("申请增重");
        int in = orderMapper.updateByPrimaryKeySelective(order);
        order dataOrder = orderMapper.selectByPrimaryKey(order.getId());
        if (in == 1) {

            log.debug("开始推送");
            //推送消息给管理员，提醒派单

            List<String> openIds = new ArrayList<>();
            //张小强
//            openIds.add("oFPgIw4CYB_mVukRGUUQxC1F0CCk");
            //肖原
            openIds.add("oFPgIw_D9SUsvqsD_uA7dDxz3eKs");
            //杨远量
            openIds.add("oFPgIw8H0Qwdw5xdLLXEstgEwzCk");
            //陆荣康
//            openIds.add("oFPgIw9PIVwv02aCzZ2IX8J8CAHM");
            //冯多飞
            openIds.add("oFPgIw_Xd7UWBrgJpZSyoDPJ4e8Y");
            //冯成
            openIds.add("oFPgIw2-8r79J6aoNrtlhA9EQzn4");
            //张松
            openIds.add("oFPgIwyIjmu5CENT5Oq5W8NlaU7U");
            //王总
            openIds.add("oFPgIw4m20hoEXIELztoUQM3YdtU");





            //1，配置
            WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
            wxStorage.setAppId("wx8153b9b18ebfa8eb");
            wxStorage.setSecret("c8bf9f0c564f7f44a297054995e6eada");
            String token = gzhMapper.selectByPrimaryKey(3).getAccessToken();
            wxStorage.setAccessToken(token);

            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(wxStorage);


            for (int i = 0; i < openIds.size(); i++) {
                WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                miniProgram.setAppid("wx1cf12dee9dbfe13c");
                miniProgram.setPagePath("pages/sendOrder/main?id=" + dataOrder.getId());
                //2,推送消息
                WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                        .toUser(openIds.get(i))//要推送的用户openid
                        .templateId("Xc_tnHReR3n1X91cwATTFitTJwgKDGn2YRhpygiA53U")//模版id
                        .miniProgram(miniProgram)
                        .build();
                //3,如果是正式版发送模版消息，这里需要配置你的信息
                templateMessage.addData(new WxMpTemplateData("first", "增重申请", "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword1", "骑手申请增重输入重量", "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword2", dataOrder.getUserName(), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword4", dataOrder.getUserPhone(), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("keyword5", dataOrder.getUserArea().substring(dataOrder.getUserArea().indexOf("市") + 1, Math.min(dataOrder.getUserArea().indexOf("市") + 20, dataOrder.getUserArea().length())), "#FF00FF"));
                templateMessage.addData(new WxMpTemplateData("remark", "点击审核", "#FF00FF"));
                //templateMessage.addData(new WxMpTemplateData("name2", value2, color2));
                try {
                    wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
                } catch (Exception e) {
                    System.out.println("推送失败：" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    @Override
    public boolean apply(String orderId) {
        order order = new order();
        order.setId(Integer.parseInt(orderId));
        order.setOrderState("增重");
        int i = orderMapper.updateByPrimaryKeySelective(order);
        if (i == 1) {
            return true;
        } else {
            return false;
        }
    }


    @Override
    public boolean toCode(int code, String phone) {
        if (!StringUtils.isNotBlank(ObjectUtils.toString(redisTemplate.get(phone + "code")))) {
            return false;
        }
        int codeRedis = (int) redisTemplate.get(phone + "code");
        if (code == codeRedis) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean register(horseman horseman) {
        int i = horsemanMapper.insertSelective(horseman);
        return i == 1;
    }

    @Override
    public Map<String, String> drive(String url) {
        gzh gzh = gzhMapper.selectByPrimaryKey(2);
        JSONObject jsonObject;
        try {
            log.debug(url);
            jsonObject = AuthUtil.doGetJson("https://api.weixin.qq.com/cv/ocr/drivinglicense?img_url=" + url + "&access_token=" + gzh.getAccessToken());
            log.debug(jsonObject.toString());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getHoresmanToken() {
        return gzhMapper.selectByPrimaryKey(2).getAccessToken();
    }

    @Override
    public double todayCount(String openId) {
        Map<String, Object> map = new HashMap<>();
        Calendar calmo = Calendar.getInstance();
        calmo.set(calmo.get(Calendar.YEAR), calmo.get(Calendar.MONTH), calmo.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        java.util.Date beginOfDate = calmo.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        java.util.Date beginevOfDate = cal.getTime();
        SimpleDateFormat formatterev = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        map.put("openId", openId);
        map.put("morning", formatter.format(beginOfDate));
        map.put("evening", formatterev.format(beginevOfDate));
        Double count = orderMapper.todayCount(map);
        log.debug(String.valueOf(count));
        if (count == null) {
            return 0;
        } else {
            return count;
        }
    }

    @Override
    public double yesterdayCount(String openId) {
        Map<String, Object> map = new HashMap<>();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date d = cal.getTime();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(d.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);

        Calendar calev = Calendar.getInstance();
        calev.add(Calendar.DATE, -1);
        Date dev = calev.getTime();
        LocalDateTime localDateTimeev = LocalDateTime.ofInstant(Instant.ofEpochMilli(dev.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDayev = localDateTimeev.with(LocalTime.MAX);


        map.put("openId", openId);
        map.put("morning", Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()));
        map.put("evening", Date.from(startOfDayev.atZone(ZoneId.systemDefault()).toInstant()));
        Double count = orderMapper.todayCount(map);
        log.debug(String.valueOf(count));
        if (count == null) {
            return 0;
        } else {
            return count;
        }
    }

    @Override
    public double orderTodayCount(String openId) {
        Map<String, Object> map = new HashMap<>();
        Calendar calmo = Calendar.getInstance();
        calmo.set(calmo.get(Calendar.YEAR), calmo.get(Calendar.MONTH), calmo.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        java.util.Date beginOfDate = calmo.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        java.util.Date beginevOfDate = cal.getTime();
        SimpleDateFormat formatterev = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        map.put("openId", openId);
        map.put("morning", formatter.format(beginOfDate));
        map.put("evening", formatterev.format(beginevOfDate));
        Double count = orderMapper.orderTodayCount(map);
        log.debug(String.valueOf(count));
        if (count == null) {
            return 0;
        } else {
            return count;
        }
    }

    @Override
    public double orderYesterdayCount(String openId) {
        Map<String, Object> map = new HashMap<>();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date d = cal.getTime();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(d.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);

        Calendar calev = Calendar.getInstance();
        calev.add(Calendar.DATE, -1);
        Date dev = calev.getTime();
        LocalDateTime localDateTimeev = LocalDateTime.ofInstant(Instant.ofEpochMilli(dev.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDayev = localDateTimeev.with(LocalTime.MAX);


        map.put("openId", openId);
        map.put("morning", Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()));
        map.put("evening", Date.from(startOfDayev.atZone(ZoneId.systemDefault()).toInstant()));
        Double count = orderMapper.orderTodayCount(map);
        log.debug(String.valueOf(count));
        if (count == null) {
            return 0;
        } else {
            return count;
        }
    }

    @Override
    public double orderTodayWeight(String openId) {
        Map<String, Object> map = new HashMap<>();
        Calendar calmo = Calendar.getInstance();
        calmo.set(calmo.get(Calendar.YEAR), calmo.get(Calendar.MONTH), calmo.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        java.util.Date beginOfDate = calmo.getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        java.util.Date beginevOfDate = cal.getTime();
        SimpleDateFormat formatterev = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        map.put("openId", openId);
        map.put("morning", formatter.format(beginOfDate));
        map.put("evening", formatterev.format(beginevOfDate));
        Double count = orderMapper.orderTodayWeight(map);
        log.debug(String.valueOf(count));
        if (count == null) {
            return 0;
        } else {
            return count;
        }
    }

    @Override
    public double orderYesterdayWeight(String openId) {
        Map<String, Object> map = new HashMap<>();
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date d = cal.getTime();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(d.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);

        Calendar calev = Calendar.getInstance();
        calev.add(Calendar.DATE, -1);
        Date dev = calev.getTime();
        LocalDateTime localDateTimeev = LocalDateTime.ofInstant(Instant.ofEpochMilli(dev.getTime()), ZoneId.systemDefault());
        LocalDateTime startOfDayev = localDateTimeev.with(LocalTime.MAX);


        map.put("openId", openId);
        map.put("morning", Date.from(startOfDay.atZone(ZoneId.systemDefault()).toInstant()));
        map.put("evening", Date.from(startOfDayev.atZone(ZoneId.systemDefault()).toInstant()));
        Double count = orderMapper.orderTodayWeight(map);
        log.debug(String.valueOf(count));
        if (count == null) {
            return 0;
        } else {
            return count;
        }
    }

    @Override
    public List<Map<String, Object>> findPackageClassify() {
        packageClassifyExample cEx = new packageClassifyExample();
        packageClassifyExample.Criteria criteria = cEx.createCriteria();
        criteria.andFidEqualTo(0);
        List<packageClassify> packageClassifys = packageClassifyMapper.selectByExample(cEx);

        List<Map<String, Object>> packageClassifyList = new ArrayList<>();
        //前端使用数据结构

        for (int i = 0; i < packageClassifys.size(); i++) {
            Map<String, Object> classifyMap = new HashMap<String, Object>();
            classifyMap.put("text", packageClassifys.get(i).getName());
            packageClassifyExample cE = new packageClassifyExample();
            packageClassifyExample.Criteria cr = cE.createCriteria();
            cr.andFidEqualTo(packageClassifys.get(i).getId());
            List<packageClassify> packageClassifys1 = packageClassifyMapper.selectByExample(cE);
            for (int j = 0; j < packageClassifys1.size(); j++) {
                packageClassifys1.get(j).setText(packageClassifys1.get(j).getName());
            }
            classifyMap.put("children", packageClassifys1);
            packageClassifyList.add(classifyMap);
        }


        return packageClassifyList;
    }



    public static Map<String, Double> getLngAndLat(String address) {
        Map<String, Double> map = new HashMap<String, Double>();
        String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address + "&output=json&ak=14fN9rWBjnBw4LGzGe7PVNtf";
        System.err.println("这里啊啊啊!!!"+url);

        String json = loadJSON(url);


        System.err.println("大哥这里啊"+json.toString());
        JSONObject obj = JSONObject.fromObject(json);
        if (obj.get("status").toString().equals("0")) {
            double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
            double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
            map.put("lng", lng);
            map.put("lat", lat);
        } else {
            System.out.println("未找到相匹配的经纬度！");
        }
        return map;
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    yc.getInputStream()));
            String inputLine = null;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
        return json.toString();
    }

}
